<template>
  <div class="common-page page-org-depts" v-loading.fullscreen="loading">
    <div class="common-page__head">
      <!-- <comp-paths class="route" :paths="['/org', $route.fullPath]"></comp-paths> -->
      <div class="title">{{ $options.title }}</div>
    </div>

    <!-- <comp-depts class="common-page__body" ref="list" select link>
            <template #head="scope">
                <el-button type="plain" size="small" icon="el-icon-refresh" @click="search()">刷新列表</el-button>
                <el-button type="primary" size="small" icon="el-icon-plus" @click="addDept()">添加部门</el-button>
                <el-button type="danger" size="small" icon="el-icon-delete" @click="delDept(...scope.selects)">删除部门</el-button>
            </template>
            <template #body="scope">
                <el-button type="plain" size="mini" @click.stop="addDept(scope.data)" :disabled="scope.data.level >= 5">添加下级部门</el-button>
                <el-button type="primary" size="mini" @click.stop="setDept('start', scope.data)">编辑</el-button>
                <el-button type="danger" size="mini" @click.stop="delDept(scope.data)">删除</el-button>
            </template>
        </comp-depts> -->
    <guandept class="common-page__body" ref="list"></guandept>
  </div>
</template>

<script>
import mixin from "../mixin";
import { string, int, deepCopy } from "../util";
import guandept from "../compents/guandept.vue";
export default {
  name: "page-org-depts",
  title: "部门管理",
  nodes: ["/menu/org"],
  childs: [],
  mixins: [mixin],
  data: () => ({
    loading: false,
    dept: null,
    provinces: [],
    citys: [],
    countys: [],
    deptCopy: null,
  }),
  components: {
    guandept,
  },
  methods: {
    search() {
      if (this.loading) return;
      // this.$nextTick(() => this.$refs.list.init());
    },
    addDept(dept) {
      if (this.loading) return;
      let target = this.plugins.user.formatDept();
      if (dept) {
        target.dept.id = dept.id;
        target.dept.name = dept.name;
        target.level = dept.level + 1;
      } else {
        target.level = 1;
      }
      this.setDept("start", target);
    },
    setDept(action, data) {
      if (this.loading) return;
      let form = this.dept;
      let provinces = this.provinces;
      let citys = this.citys;
      let countys = this.countys;
      if (!action || action === "start") {
        this.dept = deepCopy(data);
        this.deptCopy = JSON.parse(JSON.stringify(data));
        this.provinces = this.plugins.user.provinces;
        this.citys = this.plugins.user.citys;
        this.countys = this.plugins.user.countys;
        this.setDept("validate");
        this.$refs.dept.init();
        this.$nextTick(() => this.$refs.deptName.focus());
      } else if (action === "validate") {
        let error = "";
        form.name = string(form.name).trim();
        form.province.id = string(
          () =>
            provinces.find((province) => province.id === form.province.id).id
        );
        form.city.id = string(
          () =>
            citys.find(
              (city) =>
                city.id === form.city.id &&
                city.province.id === form.province.id
            ).id
        );
        form.county.id = string(
          () =>
            countys.find(
              (county) =>
                county.id === form.county.id && county.city.id === form.city.id
            ).id
        );
        error = error || (form.name ? "" : "请输入部门名称！");
        form.sort = Math.max(int(form.sort), 0) || null;
        if (data) this.plugins.modal.toast(error, "error");
        return !error;
      } else if (action === "pick-dept-start") {
        this.$refs.deptPicker.init();
        this.$nextTick(() => this.$refs.deptPickerList.init());
      } else if (action === "pick-dept-end") {
        if (data) form.dept = data;
        this.$refs.deptPicker.close();
        this.setDept("validate");
      } else if (action === "submit") {
        if (!this.setDept("validate", true)) return;
        else this.loading = true;
        if (form.id)
          this.plugins.user.setDept(form).then((res) => {
            console.log("form_____", form);
            this.loading = false;
            if (res.code === 0) {
              this.plugins.modal.toast("保存成功！", "success");
              this.setDept("end");

              this.search();
            } else {
              this.plugins.modal.alert(
                "保存失败",
                res.code + "：" + res.msg,
                "error"
              );
            }
          });
        else
          this.plugins.user.addDept(form).then((res) => {
            this.loading = false;
            if (res.code === 0) {
              this.plugins.modal.toast("添加成功！", "success");
              this.setDept("end");
              this.search();
            } else {
              this.plugins.modal.alert(
                "添加失败",
                res.code + "：" + res.msg,
                "error"
              );
            }
          });
      } else if (action === "end") {
        this.$refs.dept.close();
      }
    },
    delDept(...depts) {
      if (this.loading) return;
      if (depts.length === 0)
        return this.plugins.modal.toast("请先勾选要删除的部门哦！", "warning");
      let content =
        " <span style='color:red;'>" +
        (depts.length > 1
          ? "勾选的" + depts.length + "个部门"
          : depts[0].name) +
        "</span> 吗？";
      this.plugins.modal
        .alert("删除确认", "确定删除" + content, "warning", [
          "确定删除",
          "再想想",
        ])
        .then((ok) => {
          if (!ok) return;
          this.loading = true;
          this.plugins.user.delDept(...depts.reverse()).then((res) => {
            this.loading = false;
            if (res.code === 0) {
              this.plugins.modal.toast("删除成功！", "success");
              this.search();
            } else {
              this.plugins.modal.alert(
                "删除失败",
                res.code + "：" + res.msg,
                "error"
              );
            }
          });
        });
    },
    jiexi(list, data) {
      console.log("list", list);
      console.log("jiexi", data);
      const deptId = data.dept.id;
      for (let i in list) {
        list[i]["activated"] = false;
        if (this.deptCopy.dept.id != deptId) {
          if (deptId === list[i].id) {
            list[i].depts.push(data);
          }
        }
        if (list[i].id === data.id) {
          if (deptId && list[i].dept.id != deptId) {
            list.splice(i, 1);
          } else {
            list[i] = data;
          }
          break;
        } else {
          if (list[i].expanded) {
            this.jiexi(list[i].depts, data);
          }
        }
      }
    },
    destroy() {
      if (this.loading) return;
      return true;
    },
    init() {
      if (this.loading) return;
      this.loading = true;
      this.$root.$refs.navbar.init();
      this.plugins.user
        .call(async () => {
          let res = await this.plugins.user.init();
          if (res.code === 0) {
          }
          return res;
        })
        .then((res) => {
          this.loading = false;
          this.$root.$refs.navbar.init();
          if (res.code === 0) {
            if (this.access(this.$route.name)) {
              this.search();
            } else {
              this.$router.replace("/home");
            }
          } else if (res.code === 2) {
            this.$root.$refs.navbar.login();
          } else {
            this.plugins.modal
              .alert("页面加载失败", res.code + "：" + res.msg, "error")
              .then(() => this.$router.replace("/home"));
          }
        });
    },
  },
};
</script>

<style lang="scss">
.page-org-depts {
  overflow: hidden;
}
</style>
